package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.srb.oss.service.FileService;
import com.atguigu.srb.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * ClassName: FileServiceImpl
 * Package: com.atguigu.srb.oss.service.impl
 * Description:
 *
 * @Author 王晓龙
 * @Create 2023/3/30 17:02
 * @Version 1.0
 */
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
        //判断桶存不存在，不存在就创建，存在就获取
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            //给创建的桶子附上权限，公共读
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        //构建日期路径
        String datePath = new DateTime().toString("yyyy/MM/dd");

        //文件名：uuid.拓展名
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        //文件在服务器中的路径，文件夹+文件名
        String filePath = module + "/" + datePath + "/" + fileName;
        //文件上传至阿里云
        ossClient.putObject(OssProperties.BUCKET_NAME, filePath, inputStream);
        //关闭ossclient
        ossClient.shutdown();
        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + filePath;
    }

    @Override
    public void remove(String fileUrl) {
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);

        //拼接出文件在服务器上的访问路径前缀
        String fileUrlPrefix = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/";
        //把文件路径前缀从url里截去，获得文件名在服务器中的路径
        String fileName = fileUrl.substring(fileUrlPrefix.length());

        //把文件删除
        ossClient.deleteObject(OssProperties.BUCKET_NAME, fileName);

        //关闭ossclient
        ossClient.shutdown();
    }
}